const BaseRest = require('../rest.js')

module.exports = class extends BaseRest {
  async postAction () {
	  const pk = await this.modelInstance.pk
	  const model = this.modelInstance
	  let data = this.post()
	  delete data[pk]
	  if (think.isEmpty(data)) {
		  return this.fail('数据不能为空');
	  }
	  let goods = await this.modelInstance.where({name: data.name, manufacturer_id: data.manufacturer_id}).find()
	  if ('id' in goods) {
		  this.fail(1, '商品名重复')
		  return false
	  }
	  const insertId = await model.add(data)
    data = await model.where({id: insertId}).find()
    data.code = this.prefixInteger(data.category_id, 2) + this.prefixInteger(insertId, 3)
    await model.update(data)
	  return this.success({id: insertId})
  }
  async listAction () {
    const {page, pageSize, field, value} = this.get()
    let where = {}
    if (value) {
      where = {[field]: ['LIKE', `%${value}%`]}
    }
    let listPage = await this.modelInstance.where(where).page(page, pageSize).countSelect()
    this.success(listPage)
  }
  async categoryManufacturerAction () {
    const categoryList = await this.model('category').select()
    const manufacturerList = await this.model('manufacturer').field('id, name').select()
    this.success({category: categoryList, manufacturer: manufacturerList })
  }
  async goodsForNameAction () {
    const {name} = this.get()
    let list = await this.modelInstance.where({name: ['LIKE', `%${name}%`]}).select()
    this.success(list)
  }
}